package com_.dxy_test_.zookeeper_.app_status_;

import com_.dxy_test_.zookeeper_.ZkConfig;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * @author: dangxianyue
 * @date: 2021/4/30 08:20
 * 需求：开发一个可以监听zk中servers下面的内容发生变化的程序
 * 如果发生变化，立马执行监听器的方法（打印名单）
 */
public class ClientDemo {

    private ZkClient zk = null;

    public static void main(String[] args) throws Exception {
        ClientDemo client = new ClientDemo();
        //1:连接 zk
        client.connect();
        //2:查询所有节点
        client.showServerList();
        //3:保持程序运行
        client.keepRunning();
    }

    private void connect() throws Exception {
        zk = ZkConfig.zkClient;
        if (!zk.exists(ZkConfig.SERVERS_PATH)) {
            zk.createPersistent(ZkConfig.SERVERS_PATH);
        }

    }

    private void showServerList() throws Exception {
        System.out.println("打印服务器的名单");
        //true表示启用监听器
        List<String> servers = zk.getChildren(ZkConfig.SERVERS_PATH);
        System.out.println(servers);
        zk.subscribeChildChanges(ZkConfig.SERVERS_PATH, new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                //应用上下限此时就可以被订阅感知到，可以自己的逻辑实现推送通知给运维人员
                System.out.println("subscribeChildChanges: currentChilds: " + currentChilds);
            }
        });

    }

    private void keepRunning(){
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

